import { _decorator, Component, Node, SpriteFrame, Prefab, instantiate, Sprite, Layout, UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('CreateImgs')
export class CreateImgs extends Component {
    @property([SpriteFrame])
    public pics: SpriteFrame[] = [];
    @property(Prefab)
    public prefab: Prefab = null;
    start() {
        this.node.removeAllChildren();
    }
    createNode() {
        const arr=[];
        let num = 0;
        //随机生成图片数组
        for (let i = 0; i < this.row*this.column/2; i++) {
            num = Math.floor(Math.random() * 12);
            arr.push(num);
            arr.push(num);
        }
        //打乱顺序
        arr.sort(
            () => Math.random() - 0.5
        )
        //图片实列化
        arr.forEach((e) => {
            this.newNode = instantiate(this.prefab);
            this.newNode.getComponent(Sprite).spriteFrame = this.pics[e];
            this.newNode.getChildByName('Checkmark').getComponent(Sprite).spriteFrame = this.pics[e];
            this.arr.push(this.newNode);
            this.node.addChild(this.newNode);
        }) 
        this.node.getComponent(UITransform).height=this.column*this.newNode.getComponent(UITransform).height*this.newNode.scale.y+2*(this.column-1);
        this.node.getComponent(UITransform).width=this.row*this.newNode.getComponent(UITransform).width*this.newNode.scale.x+2*(this.row-1);
        //取消自动布局
        this.scheduleOnce(() => {
                this.node.getComponent(Layout).enabled=false;
        })
    }
    changeImgs()
    {
     try {
        this.node.removeAllChildren();
        this.node.getComponent(Layout).enabled=true;
        this.arr.sort(
            () => Math.random() - 0.5
        )
        this.arr.forEach(e => {
            if(e.active)
            this.node.addChild(e);
        });
        //取消自动布局
        this.scheduleOnce(() => {
                this.node.getComponent(Layout).enabled=false;
        })
     } catch (error) {
        console.log(error);      
     }
    }
    private newNode: Node = null;
    public arr:Node[] = [];
    public row:number=12;
    public column:number=8;
}

